<template>
  <div class="image-list">
      <!-- 单选框：按钮形式 -->
      <div class="action-head">
      <el-radio-group v-model="collect" size="mini" @change="loadImage(1)">
      <el-radio-button :label="false" >全部</el-radio-button>
      <el-radio-button :label="true" >收藏</el-radio-button>
      </el-radio-group>
       <el-button
        v-if="isShow"
        size="mini"
        type="success"
        @click="dialogUploadVisible=true"
        >
        上传素材
        </el-button>
      </div>

      <!-- 素材列表 -->
      <el-row :gutter="60">
        <el-col :xs="12" :sm="6" :lg="4" :md="6" class="image-item"
        v-for="(image,index) in images" :key="index">
           <el-image
                style="height: 100px; padding:4px;"
                :src='image.url'
                fit="cover"
                @click.native="selected=index"
                >
           </el-image>

             <div
             class="selected"
             v-if="isShowSelected && selected===index"
             ></div>

           <div class="image-action"  v-if="isShow">
          <el-button
            circle
            size="mini"
            :class="{
             'el-icon-star-on': image.is_collected,
             'el-icon-star-off': !image.is_collected
            }"
            @click="onCollect(image)"
            :loading="image.loading"
          >
          </el-button>
          <el-button
            icon="el-icon-delete"
            circle
            size="mini"
            :loading="image.loading"
            @click="onDelete(image)"
           > </el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-pagination
          background
          layout="prev, pager, next"
          :total="totalCount"
          :page-size="pageSize"
          :current-page.sync="page"
          @current-change="onPageChange"
          >
      </el-pagination>

       <!-- 弹出框 -->
      <el-dialog title="上传素材" :visible.sync="dialogUploadVisible"
      :append-to-body="true">
      <!-- upload 组件本身就支持请求提交上传操作， 不用自己去发请求，他会自己发
      请求方法：默认POST
      请求路径：action,必须写完整路径
      请求头：headers -->
        <el-upload
            class="upload-demo"
            drag
            action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
            multiple
            :headers="uploadeHeaders"
            name="image"
            :on-success="onUploadSuccess"
            :show-file-list="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png/jpeg文件，且不超过500kb</div>
        </el-upload>
      </el-dialog>
  </div>
</template>
<script>
import { getImageInfo, collectImage, deleteImage } from '@/api/image'
export default {
  name: 'ImageList',
  data () {
    const user = JSON.parse(window.localStorage.getItem('user'))
    return {
      collect: false,
      images: [], // 图片列表
      dialogUploadVisible: false, // 默认隐藏
      uploadeHeaders: {
        Authorization: `Bearer ${user.token}`
      },
      totalCount: 0, // 总数据数
      page: 1, // 当前页码
      pageSize: 10, // 每页的图片数目
      collectLoading: false, // 请求期间，禁用
      selected: null // 选中的索引
    }
  },
  methods: {
    // 获取图片列表
    loadImage(page = 1) {
      // 重置高亮页码，防止数据和页码不对应
      this.page = page
      getImageInfo({
        collect: this.collect,
        page,
        per_page: this.pageSize
      }).then(res => {
        // console.log(res)
        res.data.data.results.forEach(image => {
          image.loading = false
        })
        this.images = res.data.data.results
        this.totalCount = res.data.data.total_count
      })
    },
    // 上传素材后，弹框内容显示
    onUploadSuccess() {
      // 关闭对话框
      this.dialogUploadVisible = false
      // 更新素材列表
      this.loadImage(this.page)
      this.$message({
        type: 'success',
        message: ' 上传成功'
      })
    },
    // 页码改变时
    onPageChange(page) {
      this.loadImage(page)
    },
    // 图片收藏
    onCollect(image) {
    // 已收藏，取消收藏
    //   if (image.is_collected) {
    //     collectImage(image.id, !image.is_collected).then(res => {
    //       image.is_collected = !image.is_collected
    //       this.loadImage(this.page)
    //     })
    //   } else {
    //     // 未收藏，添加收藏
    //     collectImage(image.id, !image.is_collected).then(res => {
    //       image.is_collected = !image.is_collected
    //       this.loadImage(this.page)
    //     })
    //   }
    // }
      image.loading = true
      collectImage(image.id, !image.is_collected).then(res => {
        // 更新视图状态
        image.is_collected = !image.is_collected
        image.loading = false
        // 关闭loading
        this.loadImage(this.page)
      })
    },
    // 删除图片
    onDelete(image) {
      image.loading = true
      deleteImage(image.id).then(res => {
        this.loadImage(this.page)
        image.loading = false
        console.log(image.id)
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      })
    }
  },
  created () {
    // 页面初始化加载第一页数据
    this.loadImage(1)
  },
  props: {
    // 是否显示添加素材以及图片下方的操作【删除和收藏】
    isShow: {
      type: Boolean, // 布尔值
      default: true // 默认值，默认展示这个
    },
    isShowSelected: {
      type: Boolean, // 布尔值
      default: false // 默认值，默认展示这个
    }
  }
}
</script>

<style scoped lang = "less">
.action-head {
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
.image-item{
  position: relative
}
.image-action{
    height: 30px;
    background-color: rgb(204, 204, 204);
    opacity: 0.7; /* 设置透明度 */
    position: absolute;
    bottom: 7px;
    left: 5px;
    right: 5px;
    display: flex;
    justify-content: center;
}
.selected{
  background: url('./gou.jpeg') no-repeat;
  /* width:100px;
  height:100px; */
  background-size: cover;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0.2;
}
</style>
